package utils

import (
	"fmt"
    "net"
	"log"
	"time"
)

func PrintIP(){
	addrList, err := net.InterfaceAddrs()

	if err != nil {
		panic(err)
	}
	fmt.Println("开始打印服务端IP---")
	for _ , address := range addrList {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				fmt.Println(ipNet.IP.String())
				time.Sleep(500)
			}
		}
	}
	fmt.Println("结束打印服务端IP---")
}

func GetServerIP() (string, error) {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        return "", err
    }

    for _, addr := range addrs {
        var ip net.IP

        switch v := addr.(type) {
        case *net.IPNet:
            ip = v.IP
        case *net.IPAddr:
            ip = v.IP
        }

        // 只考虑IPv4地址，并排除本地回环地址（127.0.0.1）
        if ip.To4() != nil && !ip.IsLoopback() {
            return ip.String(), nil
        }
    }
    return "", fmt.Errorf("no valid IP address found")
}


func GetAllServerIP() []string {
	addrList, err := net.InterfaceAddrs()

	if err != nil {
		panic(err)
	}

	ips := make([]string, 0)

	for _ , address := range addrList {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ips = append(ips, ipNet.IP.String())
			}
		}
	}
	log.Println("调用GetAllServerIP获取IP集合---",ips)
	return ips
}
